import { Header } from "./components/Header";
import { useComponentsStore } from "@/stores/edit-pages-store";
import { Preview } from "./components/Preview";
import { EditView } from "./components/EditView";
import { useParams } from "react-router-dom";
import { getPage } from "@/interfaces";
import { useEffect, useState } from "react";
import { LowCodePageProvider } from "./contextProvider/LowCodePageProvider";
import { Spin } from "antd";
export default function LowCodeEditor() {
  const { preview, pages, addPage, setCurSchema, setPopEditing, setCurPopTarget, schema, setMode } = useComponentsStore();
  const {path} = useParams()
  const [loading, setLoading] = useState(true)
  async function getData(){
    if(path){
      const page = pages.find(item=>item.path===path)
      if(page){
        setCurSchema(page.schema)
      }else{
        const pageMsg = await getPage(path)
        if(pageMsg.data.data){
          const {schema, id, icon,label} = pageMsg.data.data
          addPage(path, schema, id, icon, label)
            // click编辑时，查看store是否有临时数据，如果有询问是否清除，不清除就用临时的
            //清楚=》 如果接口schema是null？init数据：接口schema
            // 刷新页面时，根据path找到schema, 设置编辑schema
        }else{
          alert('页面不存在')
          window.close()
        }
      }
    }else{
      const unknown = pages.find(item=>item.path=== "unknown")
      if(unknown){
        setCurSchema(unknown.schema)
      }else{
        addPage("unknown", "null", 0, "unknown", "未知页面")
      }
    }
    setPopEditing(false)
    setCurPopTarget(null)
    setLoading(false)
  }
  useEffect(()=>{
    setMode(false)
    getData()
  },[])

  return (
    <LowCodePageProvider>
      <div className="h-[100vh] flex flex-col">
        <div className="h-[60px] flex items-center border-b-[1px] border-gray-200">
          <Header />
        </div>
        {/* <Spin spinning={loading} fullscreen/> */}
        {loading ? null: (!preview ? <EditView /> : <Preview className="p-4"/>)}
      </div>
    </LowCodePageProvider>
  );
}
